<?php

/**
 * Authentication controller class
 *
 */
class AuthController extends Client_Controller
{
    /**
     * index action method
     *
     */

    protected $_resource_name = "auth";

    public function indexAction()
    {
    	$this->_redirect('/auth/login/');
    }

    public function loginAction()
    {
    	global $_SERVER;
    	$message = '';
    	if($this->_request->isPost()) {
			$f = new Zend_Filter_StripTags();
			$username = $f->filter($this->_request->getPost('username'));
			$password = $f->filter($this->_request->getPost('password'));

			if(empty($username)) {
				$message = 'Необходимо указать Имя пользователя.';
			}else {
				$dbAdapter = Zend_Registry::get('db');
				$authAdapter = new Zend_Auth_Adapter_DbTable(
					$dbAdapter,
					'accounts',
					'username',
					'password'
				);

				$select = $authAdapter->getDbSelect();
				$select->where('is_active = 1')
					   ->where('is_removed = 0')
					   ->where('is_ghost = 0');

				$authAdapter->setIdentity($username);
				$authAdapter->setCredential(md5($password));

				$auth_pluging = $this->getFrontController()->getPlugin('Auth');

				$auth = Zend_Registry::get('auth');//Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				if ($result->isValid()) {
					$data = $authAdapter->getResultRowObject(null, 'password');

					$role = $this->table_roles->GetRoleByID($data->role_id);
					$data->role_name = $role['name'];
					$auth->getStorage()->write($data);
					$this->_redirect($_SERVER['HTTP_REFERER']);
				} else {
					$message = 'Ошибка аутентификации.';
				}
			}

        }

    	$this->startContent();
    	$this->view->xmlWriter->startElement("main");
    	$this->view->assign('message', $message);
    	$this->view->xmlWriter->endElement();
        $this->endContent();
    }

	function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('/');
	}

	function registrationAction()
	{
		$this->startContent();
    	$this->view->xmlWriter->startElement("main");

		$data['login'] = $this->_request->getPost('login');
		$data['pass1'] = $this->_request->getPost('pass1');
		$data['pass2'] = $this->_request->getPost('pass2');
		$data['name'] = $this->_request->getPost('name');
		$data['email'] = $this->_request->getPost('email');

		$msg = '';

		if($this->_request->isPost())
		{
			$captcha = new Gnews_Captcha('asdas asda sda sdasd');
            if($captcha->valid($this->_request->getPost('code')))
            {
				if(!$this->accounts_table->insert($data))
				{
					$data['pass1'] = $data['pass2'] = '';
					$msg = $this->accounts_table->_ERROR;
				}
				else foreach($data as $k => $v) $data[$k] = '';
            }else $msg= 'Не верное подтвержение кода.';
		}

		$this->view->assign('message', $msg);
		$this->view->assign('form_data', $data);

    	$this->view->xmlWriter->endElement();
        $this->endContent();
	}
}
